#include "database.hpp"
#include "mystring.hpp"
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace poly;

void database::clear() {
	db->clear();
}

int getparam(char *&f,hash &h) {
	char *s=getword(f);
	return h.get(s);
}

void database::insert(char *f) {
	entry tk;
	tk.time=getparam(f,htime);
	tk.place=getparam(f,hplace);
	tk.subject=getparam(f,hsubject);
	tk.teacher=getparam(f,hteacher);
	tk.group=getparam(f,hgroup);
	db->ins(tk);
}

void database::load(const char * dbname, const char * propname) {
	printf("Loading configuration (%s)\n",propname);
	fflush(stdout);
	FILE *in=fopen(propname,"r");
	fscanf(in,"%d",&time_c);
	for (int i=0;i<time_c;i++) {
		char *s=new char[MAXELEM];
		fscanf(in,"%s",s);
		htime.get(s);
	}
	fscanf(in,"%d",&place_c);
	for (int i=0;i<time_c;i++) {
		char *s=new char[MAXELEM];
		fscanf(in,"%s",s);
		hplace.get(s);
	}
	fclose(in);
	db=new sparce_table(time_c-1,place_c-1);
	printf("Loading database (%s)\n",dbname);
	in=fopen(dbname,"r");
	while (1) {
		char *s=new char[MAXQUERY];
		if (fgets(s,MAXQUERY,in)==0) break;
		manage_query(s);
	}
}

void database::save(const char * filename) {
	FILE *out = fopen(filename, "w");
	list<entry> rs=db->find(0,time_c-1,0,place_c-1);
	for (list<entry>::iterator i=rs.begin();i!=rs.end();i++) {
		char *t1=htime.str((*i).time);
		char *t2=hplace.str((*i).place);
		char *t3=hsubject.str((*i).subject);
		char *t4=hteacher.str((*i).teacher);
		char *t5=hgroup.str((*i).group);
		fprintf(out,"insert %s %s %s %s %s\n",t1,t2,t3,t4,t5);
	}
	fclose(out);
}

const char *database::manage_query(const char *query) {
	printf("Manage query: '%s'\n",query);
	char *q=(char *)query;
	char *com=getword(q);
	printf("The command is '%s'\n",com);
	if (strcmp(com,"insert")==0) insert(q); else
	if (strcmp(com,"save")==0) save(getword(q)); else
	if (strcmp(com,"load")==0) {
		char *s=getword(q),*t=getword(q);
		load(s,t); 
	}else 
	if (strcmp(com,"")==0) return "Empty command"; else
	{
		return "Unknown operation";
	}
	printf("Query success.");
	return "Ok";
}
